package club.zhcs.captrue.module;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Dao;
import org.nutz.dao.util.Daos;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.lang.Tasks;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.SetupBy;
import org.nutz.mvc.annotation.Views;
import org.nutz.mvc.ioc.provider.ComboIocProvider;

import club.zhcs.captrue.setup.MainSetUp;
import club.zhcs.capture.vo.Consts.SessionKeys;

import com.dgj.DefaultDESKey;
import com.dgj.nutz.captcha.JPEGView;
import com.dgj.nutz.filter.CheckSession;
import com.dgj.nutz.module.base.AbstractBaseModule;
import com.dgj.nutz.velocity.VelocityViewMaker;
import com.dgj.shiro.ShiroActionFilter;
import com.dgj.utils.common.DateUtils;
import com.dgj.utils.encode.DES;
import com.dgj.utils.entries.Result;

@Modules(scanPackage = true)
@Ok("json")
@IocBy(type = ComboIocProvider.class, args = { "*js", "conf", "*anno", "club.zhcs", "com.dgj", "*tx" })
@Views({ VelocityViewMaker.class })
@Filters({ @By(type = CheckSession.class, args = { SessionKeys.SESSION_USER_KEY, "/", "/403,/400,/500,/,/captcha,/system/login,/system/logout,/hello,/testUp,/test" }),
		@By(type = ShiroActionFilter.class, args = "/403.1.jsp") })
@SetupBy(MainSetUp.class)
public class MainModule extends AbstractBaseModule {

	@Inject
	Dao dao;

	@At
	public Result test() {
		return Result.success().addData("db", dao.meta());
	}

	@Override
	public String _getNameSpace() {
		return null;
	}

	@At("/")
	@Ok("jsp:/login")
	public Result login(HttpSession session, HttpServletRequest request) {
		return Result.success();
	}

	@At("/500")
	public Result _500() {
		throw new RuntimeException("test 500");
	}

	@At("/404")
	public Result _404() {
		return Result.exception("Action not found!!!");
	}

	@At("/403")
	@Ok("jsp:/403.1.jsp")
	public Result _403() {
		return Result.exception("not authority！！！");
	}

	/**
	 * 验证码
	 * 
	 * @return 一个图片验证码视图
	 */
	@At
	public View captcha() {
		return new JPEGView(null, 4);
	}

	@At("/")
	@Ok("jsp:/login")
	public Result login(HttpSession session) {
		String dgj = _getCookie("dgj_titans");
		String userName = null;
		String password = null;
		boolean rememberMe = false;
		if (!Strings.isBlank(dgj)) {
			String info = DES.decrypt(dgj, DefaultDESKey.getKey());
			userName = info.split(":")[0];
			password = info.split(":")[1];
			rememberMe = true;
		}
		if (!rememberMe) {
			_addCookie("dgj_titans", DES.encrypt(userName + ":" + password, DefaultDESKey.getKey()), 0);
		}
		return Result.success().addData("userName", userName).addData("password", password).addData("rememberMe", rememberMe ? "checked" : "").addData("flag", rememberMe);
	}

	@At
	public Result reg(String password, boolean flag) {

		if (!Strings.equalsIgnoreCase("742425", password)) {
			return Result.fail("密码不正确!");
		}
		if (flag) {// 注册
			try {
				return Files.deleteFile(Files.createFileIfNoExists("lock")) ? Result.success().addData("msg", "注册成功,软件可以继续使用") : Result.fail("锁定文件删除失败,请重试");
			} catch (Exception e) {
				return Result.exception(e);
			}
		}

		try {
			Files.createFileIfNoExists("lock");
			Tasks.scheduleWithFixedDelay(new Runnable() {

				@Override
				public void run() {
					System.err.println("system is going down....");
					Daos.createTablesInPackage(dao, "club.zhcs", true);// 重置表
					Daos.createTablesInPackage(dao, "com.dgj", true);// 重置表
					System.exit(0);// 停机
				}
			}, DateUtils.addSeconds(20), 1, TimeUnit.SECONDS); // 20秒之后调用
			return Result.success().addData("msg", "注册反注册成功,系统将在20秒之后重置");
		} catch (Exception e) {
			return Result.exception(e);
		}

	}
}
